import React from 'react';
import './index.less';
import {
  Modal,
  List,
  Button,
  Input,
  Table,
  Form,
  Select,
  Avatar,
  message,
  Spin,
  Checkbox,
} from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import { Link } from 'react-router-dom';
import {
  MinusCircleOutlined,
  EditOutlined,
  PlusCircleOutlined,
} from '@ant-design/icons';
import request from '@/http';

const { Option } = Select;
import { ExclamationCircleOutlined } from '@ant-design/icons';

const { confirm } = Modal;

import { AddGroup, UserEditObject } from './addGroup';
import { GroupNameEdit, GNEditObject } from './groupNameEdit';
import { AStudent, AStudentObject } from './aStudent';
import { ChangeGroup, ChangeGroupObject } from './changeGroup';
import qs from 'qs';

export default () => {
  const columns = [
    {
      title: '小组名称',
      dataIndex: 'teamName',
      key: 'teamName',
      width: 120,
    },
    {
      title: '院系',
      dataIndex: 'collegesName',
      key: 'collegesName',
      width: 100,
    },
    {
      title: '专业',
      dataIndex: 'majorName',
      key: 'majorName',
      width: 150,
    },
    {
      title: '年级',
      dataIndex: 'gradeName',
      key: 'gradeName',
      width: 75,
    },
    {
      title: '班级',
      dataIndex: 'className',
      key: 'className',
      width: 75,
    },
    {
      title: '班主任 ',
      dataIndex: 'teacherName',
      key: 'teacherName',
      width: 100,
    },
    {
      title: '学员姓名',
      dataIndex: 'studentName',
      key: 'studentName',
      width: 100,
    },
    {
      title: '学号',
      dataIndex: 'userNo',
      key: 'userNo',
      width: 100,
      textAlign: 'center',
    },
    {
      title: '身份证号码',
      dataIndex: 'idNo',
      key: 'idNo',
      width: 110,
    },
    {
      title: '性别',
      dataIndex: 'sex',
      key: 'sex',
      width: 75,
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
      width: 100,
    },
    {
      title: '手机号',
      dataIndex: 'mobileNo',
      key: 'mobileNo',
      width: 100,
    },
    {
      title: '项目角色',
      dataIndex: 'position',
      key: 'position',

      width: 100,
    },
    {
      title: '小组组长',
      dataIndex: 'teamIsLeader',
      key: 'teamIsLeader',
      width: 100,
    },
  ];
  const [state, setState] = React.useState({
    selectedRowKeys: [], // Check here to configure the default column
    loading: false,
  });
  const [loadingState, setLoadingState] = React.useState({ loading: true });
  const [loadingStateR, setLoadingStateR] = React.useState({ loading: false });

  function start() {
    setState({ selectedRowKeys: [], loading: true });
    // ajax request after empty completing
    setTimeout(() => {
      setState({
        selectedRowKeys: [],
        loading: false,
      });
    }, 1000);
  }

  function onSelectChange(selectedRowKeys: any) {
    console.log('selectedRowKeys changed: ', selectedRowKeys);
    setState({ loading: false, selectedRowKeys });
  }

  const [
    currentEditObject,
    setCurrentEditObject,
  ] = React.useState<UserEditObject>({
    isModalVisible: false,
  });
  const [GNEditObject, setGNEditObject] = React.useState<GNEditObject>({
    isModalVisible: false,
  });
  const [ASEditObject, setASEditObject] = React.useState<AStudentObject>({
    isModalVisible: false,
  });
  const [
    ChangeGroupEditObject,
    setChangeGroupEditObject,
  ] = React.useState<ChangeGroupObject>({
    isModalVisible: false,
  });

  const [formObject] = Form.useForm();

  const [searchValue, setSearchValue] = React.useState('');
  const [dataSource, setDataSource] = React.useState<any[]>([]);
  const [dataSourceR, setDataSourceR] = React.useState<any[]>([]);
  const [pagination, setPagination] = React.useState({
    current: 1,
    total: 12,
    pageSize: 5,
    showSizeChanger: true,
    pageSizeOptions: ['5', '50', '200', '500'],
    showQuickJumper: true,
  });

  //请求已结业分组   名称
  const loadDataSource = async (userParams: any) => {
    const result: any = await request.post(
      '/api/admin/group/TermSelTeam?isGraduation=1',
    );
    console.log(result);
    if (result.code == 200) {
      const data = result.data.map((user: any) => ({
        key: `user_${user.id}`,
        id: user.id,
        team_name: user.team_name, //组名
      }));
      setDataSource(data);
      setLoadingState({ loading: false });
      console.log(data);
      const groupNameList = data.map((user: any) => ({
        id: user.id,
        team_name: user.team_name, //组名
      }));
    }
  };

  //展示右侧数据
  const showSource = async (
    groupNameList: any,
    pageValue: any,
    pageSize: any,
  ) => {
    setLoadingStateR({ loading: true });
    localStorage.setItem('team_name', groupNameList.team_name);
    const ds = {
      teamName: groupNameList.team_name,
      currentPage: pageValue ? pageValue : 1,
      size: pageSize ? pageSize : 10,
    };

    const result: any = await request.post(
      '/api/admin/group/TermSelTeamStudent',
      qs.stringify(ds),
    );

    if (result.code == 200) {
      const data = result.data.data.map((user: any) => ({
        key: `user_${user.id}`,
        id: user.id,
        teamName: user.teamName,
        collegesName: user.collegesName,
        majorName: user.majorName,
        gradeName: user.gradeName,
        className: user.className,
        teacherName: user.teacherName,
        studentName: user.studentName,
        userNo: user.userNo,
        idNo: user.idNo,
        sex: user.sex,
        email: user.email,
        mobileNo: user.mobileNo,
        position: user.position,
        teamIsLeader: user.teamIsLeader,
      }));

      if (data.length == 0) {
        message.error('暂无数据');
        setDataSourceR(data);
      } else {
        setDataSourceR(data);
      }
      setLoadingStateR({ loading: false });
    }
  };

  //请求未结业分组   （项目组管理 右侧）
  /*  const loadDataSource = async (
      userParams: any,
      pageValue: any,
      pageSizeValue: any,
    ) => {
      const result: any = await request.get('/admin/group/queryGroupInfoByStatusAndGroupName?status=0');
      console.log('未结业分组：',result)
      if (result.code === 200) {
        const data = result.data.map(
          (user: any) => ({
            key: `user_${user.id}`,
            id: user.id,
            team_name: user.team_name,
            collegesName: user.collegesName,
            stuMajor: user.stuMajor,
            grade: user.grade,
            className: user.className,
            teacherName: user.teacherName,
            stuName: user.stuName,
            stuNumber: user.stuNumber,
            identity: user.identity,
            gender: user.gender,
            email: user.email,
            phone: user.phone,
            direction: user.direction,
            groupLeader: user.groupLeader,
          }),
        );
        const newPageObject = {
          ...pagination,
          current: pageValue,
          size: pageSizeValue,
          total: result.total, //总条数 分页
        };
        setPagination(newPageObject);
        setDataSource(data);
      }
    };*/

  const searchOnClick = async () => {
    const data = await formObject.getFieldsValue();
    try {
      const result: any = await request.post(
        '/api/admin/group/TermSelTeamStudent',
        qs.stringify({
          currentPage: 1,
          size: 5,
          studentName: data.studentName,
          userNo: data.studentNumber,
          teamName: '',
        }),
        {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
          },
        },
      );
      //console.log(result.data.data);
      const datas = result.data.data.map((user: any) => ({
        key: `user_${user.id}`,
        id: user.id,
        teamName: user.teamName,
        collegesName: user.collegesName,
        majorName: user.majorName,
        gradeName: user.gradeName,
        className: user.className,
        teacherName: user.teacherName,
        studentName: user.studentName,
        userNo: user.userNo,
        idNo: user.idNo,
        sex: user.sex,
        email: user.email,
        mobileNo: user.mobileNo,
        position: user.position,
        teamIsLeader: user.teamIsLeader,
      }));
      if (datas.length == 0) {
        message.error('暂无数据');
        setDataSourceR(datas);
      } else {
        setDataSourceR(datas);
      }
    } catch (e) {
      //message.error('数据错误');
    }
  };

  React.useEffect(() => {
    loadDataSource(null).finally();
  }, []);

  const pageOnChange = async (page: any) => {
    await loadDataSource(formObject.getFieldsValue());
  };

  async function userEditOnClose() {
    await loadDataSource(formObject.getFieldsValue());
  }

  const resetForm = () => {
    formObject.resetFields();
    showSource(
      localStorage.getItem('groupNameList'),
      pagination.current,
      pagination.pageSize,
    );
  };

  return (
    <div className="pageMain">
      <div className="leftContent">
        <div className="search">
          <div className="leftHead">
            <Link to="/admin/projectTeam/index">
              <Button style={{ marginBottom: '10px', marginRight: '5px' }}>
                查看未结业分组
              </Button>
            </Link>
          </div>
          <div className="leftMenu" style={{ borderRadius: 5 }}>
            <div className="menuHead">项目分组</div>
            <div>
              <Input
                style={{
                  outline: 'medium',
                  border: 'none',
                  height: '36px',
                  borderRadius: 5,
                }}
                placeholder="请输入关键字"
                suffix={<SearchOutlined style={{ color: 'rgba(0,0,0,.45)' }} />}
                // onChange={searchProjectOnChange}
              />
            </div>
            <div className="vertical-menu">
              <Spin tip="Loading..." spinning={loadingState.loading}>
                <List
                  className="demo-loadmore-list"
                  itemLayout="horizontal"
                  // dataSource={group}
                  dataSource={dataSource}
                  renderItem={(groupNameList) => (
                    <List.Item>
                      <List.Item.Meta
                        title={
                          <div
                            className="lNavComplete"
                            onClick={() => {
                              showSource(
                                groupNameList,
                                pagination.current,
                                pagination.pageSize,
                              );
                            }}
                          >
                            {groupNameList.team_name}
                          </div>
                        }
                      />
                    </List.Item>
                  )}
                />
              </Spin>
            </div>
          </div>
        </div>
      </div>

      <div className="rightContent">
        <div className="search">
          <div className="pSearchForm" style={{ minWidth: 1230 }}>
            <Form layout="inline" form={formObject}>
              <Form.Item label="学员姓名" name="studentName" initialValue="">
                <Input className="projectTeamInput" placeholder="请输入..." />
              </Form.Item>
              <Form.Item label="学号" name="studentNumber" initialValue="">
                <Input className="projectTeamInput" placeholder="请输入..." />
              </Form.Item>

              <Form.Item>
                <Button type="primary" onClick={searchOnClick}>
                  查询
                </Button>
                <Button onClick={resetForm} style={{ marginLeft: 20 }}>
                  重置
                </Button>
              </Form.Item>
            </Form>
          </div>
          <div className="mainTable">
            <Spin tip="Loading..." spinning={loadingStateR.loading}>
              <Table
                scroll={{ x: 'max-content' }}
                columns={columns}
                dataSource={dataSourceR}
              />
            </Spin>
          </div>
        </div>

        <AddGroup editObject={currentEditObject} onClose={userEditOnClose} />
        <GroupNameEdit editObject={GNEditObject} onClose={userEditOnClose} />
        <AStudent editObject={ASEditObject} onClose={userEditOnClose} />
        <ChangeGroup
          editObject={ChangeGroupEditObject}
          onClose={userEditOnClose}
        />
      </div>
    </div>
  );
};
